package handler

import (
	"art/cache"
	"art/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"log"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Article{
		//Model:   gorm.Model{},
		Title:   title,
		Content: content,
		Author:  author,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	//
	rdeis_key := "article_" + strconv.Itoa(int(data.ID))
	var article model.Article
	model.DB.Where("id = ?", data.ID).First(&article)
	jsonData, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, rdeis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func Del(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	err := model.DB.Where("id=?", id).Delete(&model.Article{}).Error
	log.Printf("删除文章失败，ID: %s, 错误: %v", id, err)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "article_" + strconv.Itoa(id)
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
func List(c *gin.Context) {
	var article []model.Article

	redis_key := "article_list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": article,
	})
}
